import logging

import log_setup

def merge_default(val1, val2, merge_methods={}, parent_keys=() ):
    """ Simple merge, handling complex merges. """
    from core import dict_merge # to avoid cyclical imports
    if val1 is not None and val2 is None:
        return val1
    type1 = type(val1)
    type2 = type(val2)
    if type1 is list:
        if type2 is list:
            return val1 + val2
        else:
            return val1 + [val2]
    if type1 is dict:
        if type2 is dict:
            return dict_merge(val1, val2, merge_methods, parent_keys)
        else:
            raise Exception('Data structure mismatch.')
    if type2 is list:
        return [val1] + val2
    # Finally, just merge two distinct values into a list.
    return [val1, val2]

def merge_first(val1, val2, merge_methods={}, parent_keys=() ):
    return val1
           
def merge_list_items(list1, list2, merge_methods={}, parent_keys=() ):
    """
    Merge list items at same index in list1 and list2.
    """
    merged = []
    try:
        list1.__iter__
    except AttributeError:
        list1 = [ list1 ]
    try:
        list2.__iter__
    except AttributeError:
        list2 = [ list2 ]
        
    for a, b in zip(list1, list2):
        # Lookup the correct method, by compound key, then by simple key.
        compound_key = tuple(list(parent_keys) + [ '#' ])
        method = merge_methods.get(compound_key, merge_methods.get('#', merge_default))
        logging.debug('Merging with method "%s"' % method.__name__)
        
        merged_item = method(a, b, merge_methods, compound_key) 
        
        logging.debug('Merged %s and %s into %s' % (a, b, merged_item))
        merged.append(merged_item)
        
    if len(list1) < len(list2):
        merged.extend( list2[len(list1):] )
    if len(list2) < len(list1):
        merged.extend( list1[len(list2):] )    
    return merged
